﻿using System;
using System.Collections.Generic;
using UnityEngine;


namespace RStudio.InputManager
{
    /// <summary>
    /// 输入中心
    /// </summary>
    public class InputCenter
    {
        public InputCenter()
        {
            InteractionTargets = new HashSet<GameObject>();
        }


        /// <summary>
        /// 交互缓存清单
        /// </summary>
        public static HashSet<GameObject> InteractionTargets { get; private set; }




        /// <summary>
        /// 获取
        /// </summary>
        public static T Get<T>(GameObject target) where T:Component, IInteraction
        {
            if (target == null)
            {
                Debug.LogError("目标对象为null，无法获取交互组件！");
                return null;
            }

            bool isContain = InteractionTargets.Contains(target);

            if (!isContain)
            {
                bool isGet = target.TryGetComponent(out T component);
                if (isGet)
                {
                    InteractionTargets.Add(target);
                    TrackTargetLifecycle(target);
                    return component;
                }
                component = target.AddComponent<T>();
                InteractionTargets.Add(target);
                TrackTargetLifecycle(target);
                return component;
            }

            return target.GetComponent<T>();
        }

        /// <summary>
        /// 移除
        /// </summary>
        public static void Remove(GameObject target)
        {
            if (target == null)
            {
                Debug.LogError("目标对象为null，无法移除交互组件！");
                return;
            }

            if (!InteractionTargets.Contains(target))
            {
                Debug.LogWarning($"交互管理器未记录该对象[{target.name}]，无需移除。");
                return;
            }

            // 移除所有实现IInteraction的组件
            var interactions = target.GetComponents<IInteraction>();
            foreach (var interaction in interactions)
            {
                interaction.Dispose();
                UnityEngine.GameObject.Destroy(interaction as Component);
            }

            InteractionTargets.Remove(target);
        }

        /// <summary>
        /// 监听目标对象销毁事件，自动清理缓存（避免内存泄漏）
        /// </summary>
        private static void TrackTargetLifecycle(GameObject target)
        {
            if (target == null) return;
            // 添加生命周期追踪组件（确保对象销毁时清理缓存）
            var tracker = target.GetComponent<InteractionLifecycleTracker>()
                         ?? target.AddComponent<InteractionLifecycleTracker>();
            tracker.RegisterOnDestroy(() => InteractionTargets.Remove(target));
        }
    }

    /// <summary>
    /// 辅助组件：用于监听对象销毁事件
    /// </summary>
    public class InteractionLifecycleTracker : MonoBehaviour
    {
        private Action _onDestroy;

        public void RegisterOnDestroy(Action callback)
        {
            _onDestroy += callback;
        }

        private void OnDestroy()
        {
            _onDestroy?.Invoke();
        }
    }
}
